#include <iostream>
#include <memory>
#include <unistd.h>
#include "TcpServer.hpp"
#include "Protocol.hpp"

void _Calcolator(Response* response,Request& request)
{
    char ch=request._op;
    switch(ch)
    {
        case '+':
        {
            response->_code=0;
            response->_result=request._x+request._y;
            break;
        }
        case '-':
        {
            response->_code=0;
            response->_result=request._x-request._y;
            break;
        }
        case '*':
        {
            response->_code=0;
            response->_result=request._x*request._y;
            break;
        }
        case '/':
        {
            if(request._y==0) 
            {
                response->_code=1;
                break;
            }
            response->_code=0;
            response->_result=request._x/request._y;
            break;
        }
        case '%':
        {
            if(request._y==0) 
            {
                response->_code=2;
                break;
            }
            response->_code=0;
            response->_result=request._x%request._y;
            break;
        }
        default :
        {
            response->_code=3;
            break;
        }
    }
}

void Calcolator(int sockfd)
{
    std::string content;
    while(true)
    {
        char buffer[1024];
        bzero(buffer,sizeof(buffer));
        ssize_t s=recv(sockfd,buffer,sizeof(buffer)-1,0);
        if(s>0)
        {
            buffer[s]='\0';
            content+=buffer;
            std::string package=Decode(content);
            if(package.empty())continue;
            //得到了完整的数据
            Request request;
            request.Deserialization(package);
            Response response;
            _Calcolator(&response,request);
            std::string messages=response.Serialization();
            std::string res=Encode(messages);
            send(sockfd,res.c_str(),res.size(),0);
            LogMessage(NORMAL,"server send success\n");
        }
        else if(s==0)
        {
            LogMessage(NORMAL,"aside close,me too....\n");
            break;
        }
        else
        {
            LogMessage(ERROR,"server recv error!!!\n");
            break;
        }
    }
    close(sockfd);
}

int main()
{
    std::unique_ptr<TcpServer> ptr(new TcpServer(8080));
    ptr->Start(Calcolator);
    return 0;
}